package com.isecta.maplew.webs;

import com.isecta.maplew.utility.HttpHelper;
import com.isecta.maplew.utility.IConstant;
import com.isecta.maplew.utility.NGFXMailRunner;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author Mithun
 */
@WebServlet(name = "ReaderNGFXWS", urlPatterns = {"/ReaderNGFXWS"})
public class ReaderNGFXWS extends HttpServlet {

    private static Logger log = Logger.getLogger(ReaderNGFXWS.class);
    private NGFXMailRunner mailRunner;

    public NGFXMailRunner getNGFXMailRunner() {
        if (mailRunner == null) {
            mailRunner = new NGFXMailRunner();
        }
        return mailRunner;
    }

    public void setNGFXMailRunner(NGFXMailRunner mailRunner) {
        this.mailRunner = mailRunner;
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected synchronized void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<Response>");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (!this.authenticate(username, password)) {
                sb.append("<errorcode>000</errorcode><message>Authenticate failed !!!</message></Response>");
                out.println(sb.toString());
                return;
            }
            String email = request.getParameter("email");
            String ePassword = request.getParameter("epassword");
            if (email == null || email.isEmpty() || ePassword == null || ePassword.isEmpty()) {
                sb.append("<errorcode>000</errorcode><message>Email and email password can not be empty.</message></Response>");
                out.println(sb.toString());
                return;
            }

            String links = this.getNGFXMailRunner().readGmail(email, ePassword);
            sb.append(links).append("</Response>");

            out.println(sb.toString());
        } catch (Throwable ex) {
            log.error("processRequest:: error " + ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean authenticate(String name, String pass) {
        try {
            if ((name == null || name.isEmpty()) && (pass == null || pass.isEmpty())) {
                log.debug("User name and password can not be empty");
                return false;
            }
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=ngfxuser/webLogin&username=" + name + "&password=" + pass;
            String response = HttpHelper.post(new URL(uri), "");

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("LoginResponse/errorcode");
            if (errorCode.equalsIgnoreCase("000")) {
                String msg = document.valueOf("LoginResponse/message");
                log.debug("authenticate :: " + msg);
                return false;
            } else {
                String msg = document.valueOf("LoginResponse/message");
                log.debug("authenticate:: " + msg);
                return true;
            }
        } catch (Throwable ex) {
            log.error("authenticate: error on authenticattion " + ex);
        }
        return false;
    }
}
